import { createStore, Store, useStore } from 'vuex'
import { IRootState, IStoreType } from './types'

import login from './login/login'
import system from './main/system/index'
import analysis from './main/analysis/dashboard'
import { getPageList } from '@/service/main/system'

const store = createStore<IRootState>({
  state() {
    return {
      entireDepartment: [],
      entireRole: [],
      entireMenu: []
    }
  },
  mutations: {
    changeEntireDepartment(state, entireDepartment: any) {
      state.entireDepartment = entireDepartment
    },
    changeEntireRole(state, entireRole: any) {
      state.entireRole = entireRole
    },
    changeEntireMenu(state, entireMenu: any) {
      state.entireMenu = entireMenu
    }
  },
  getters: {},
  actions: {
    async getInitialDataAction({ commit }) {
      // 获取所有部门列表
      const departmentResult = await getPageList('/department/list', {
        offset: 0,
        size: 1000
      })
      const { list: departmentList } = departmentResult.data

      // 获取所有角色列表
      const roleResult = await getPageList('/role/list', {
        offset: 0,
        size: 1000
      })
      const { list: roleList } = roleResult.data

      // 获取所有菜单列表
      const menuResult = await getPageList('/menu/list', {
        offset: 0,
        size: 1000
      })
      const { list: menuList } = menuResult.data

      commit('changeEntireDepartment', departmentList)
      commit('changeEntireRole', roleList)
      commit('changeEntireMenu', menuList)
    }
  },
  modules: {
    login,
    system,
    analysis
  }
})

// 重载vuex
export function setupStore() {
  store.dispatch('login/ReloadLoginInfo')
  // store.dispatch('getInitialDataAction')
}

export function useVuexState(): Store<IStoreType> {
  return useStore()
}

export default store
